<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .box {
            width: 200px;
            height: 200px;
            position: absolute;
            background: aqua;
        }
    </style>
</head>

<body>
    <div class="box"></div>
</body>
<script>
    var box = document.getElementsByClassName('box')[0]
    var maxLeft = document.documentElement.clientWidth - box.clientWidth
    var maxTop = document.documentElement.clientHeight - box.clientHeight


    window.onresize = function () {
        maxLeft = document.documentElement.clientWidth - box.clientWidth;
        maxTop = document.documentElement.clientHeight - box.clientHeight;
    }

    document.onmousemove = function (e) {
        var e = e || window.event
        var x = e.pageX - box.clientWidth / 2
        var y = e.pageY - box.clientHeight / 2

        if (x <= 0) x = 0
        if (x >= maxLeft) x = maxLeft
        if (y <= 0) y = 0
        if (y >= maxTop) y = maxTop

        // x = Math.min(Math.max(x, 0), maxLeft)
        // y = Math.min(Math.max(y, 0), maxTop)

        box.style.left = x + 'px'
        box.style.top = y + 'px'
    }

</script>

</html>